package com.lf.sp.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lf.sp.common.Const;
import com.lf.sp.common.ResponseCode;
import com.lf.sp.common.ServerResponse;
import com.lf.sp.dao.CategoryMapper;
import com.lf.sp.dao.ProductMapper;
import com.lf.sp.pojo.Category;
import com.lf.sp.pojo.Product;
import com.lf.sp.service.ICategoryService;
import com.lf.sp.service.IProductService;
import com.lf.sp.util.DateTimeUtil;
import com.lf.sp.util.PropertiesUtil;
import com.lf.sp.vo.ProductDetailVo;
import com.lf.sp.vo.ProductListVo;

@Service("iProductSercie")
public class ProductServiceImpl implements IProductService {
	@Autowired
	private ProductMapper productMapper;
	
	@Autowired
	private CategoryMapper categoryMapper;
	
	@Autowired
	private ICategoryService iCategoryService;

	@Override
	public ServerResponse saveOrUpdateProduct(Product product) {
		if (product == null) {
			return ServerResponse.createByErrorMessage("传入的参数不正确");
		}
		if (!StringUtils.isBlank(product.getSubImages())) {
			String[] subImageArray = product.getSubImages().split(",");
			if (subImageArray.length > 0) {
				product.setMainImage(subImageArray[0]);
			}
		}
		if (product.getId() == null) {
			int resultCount = productMapper.insert(product);
			if(resultCount > 0){
				
				return ServerResponse.createBySuccessMessage("添加成功");
			}else{
				return ServerResponse.createByErrorMessage("添加失败");
			}
		}else{
			int resultCount = productMapper.updateByPrimaryKey(product);
			if(resultCount > 0){
				return ServerResponse.createBySuccessMessage("更新成功");
			}else{
				return ServerResponse.createByErrorMessage("更新失败");
			}
		}
	}
	@Override
	public ServerResponse setSaleStatus(Integer productId,Integer status){
		if(productId == null || status == null){
			return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
		}
		Product product = new Product();
		product.setId(productId);
		product.setStatus(status);
		int resultCount = productMapper.updateByPrimaryKeySelective(product);
		if(resultCount > 0){
			return ServerResponse.createBySuccessMessage("更新成功");
		}
		return ServerResponse.createByErrorMessage("更新失败");
	}
	@Override
	public ServerResponse<ProductDetailVo> getDetail(Integer productId){
		if(productId == null){
			return ServerResponse.createByErrorMessage("错误，传入的参数有误");
		}
		Product product = productMapper.selectByPrimaryKey(productId);
		if(product == null){
			return ServerResponse.createByErrorMessage("未查询到信息");
		}
		//vo对象-- value Object
		//pojo->bo(businsess object) -> vo(view object)
		ProductDetailVo productDetailVo = this.assembleProductDetailVo(product);
		return ServerResponse.createBySuccess(productDetailVo);
	}
	
	private ProductDetailVo assembleProductDetailVo(Product product){
		ProductDetailVo productDetailVo = new ProductDetailVo();
		productDetailVo.setId(product.getId());
		productDetailVo.setSubtitle(product.getSubtitle());
		productDetailVo.setPrice(product.getPrice());
		productDetailVo.setMainimage(product.getMainImage());
		productDetailVo.setSubImage(product.getSubImages());
		productDetailVo.setCategoryId(product.getCategoryId());
		productDetailVo.setDetail(product.getDetail());
		productDetailVo.setName(product.getName());
		productDetailVo.setStatus(product.getStatus());
		productDetailVo.setStock(product.getStock());
		
		productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));
		
		Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
		if(category == null){
			productDetailVo.setParentCategoryId(0);
		}
		productDetailVo.setParentCategoryId(category.getParentId());
		
		productDetailVo.setCreateTime(DateTimeUtil.DateToStr(product.getCreateTime()));
		productDetailVo.setUpdateTime(DateTimeUtil.DateToStr(product.getUpdateTime()));
		//imageHost
		//parentCategoryId
		//createTime
		//updateTime
		return productDetailVo;
	}
	@Override
	public ServerResponse<PageInfo> getProductList(int pageNum, int pageSize){
		//startPage--start
		//填充自己的sql查询逻辑
		//pageHelper--收尾
		PageHelper.startPage(pageNum,pageSize);
		List<Product> productList = productMapper.selectList();
		List<ProductListVo> productListVoList = new ArrayList<ProductListVo>();
		for (Product product : productList) {
			ProductListVo productListVo = this.assembleProductListVo(product);
			productListVoList.add(productListVo);
		}
		PageInfo pageResult = new PageInfo(productList);
		pageResult.setList(productListVoList);
		return ServerResponse.createBySuccess(pageResult);
		
	}
	
	private ProductListVo assembleProductListVo(Product product){
		ProductListVo productListVo = new ProductListVo();
		productListVo.setId(product.getId());
		productListVo.setName(product.getName());
		productListVo.setCategoryId(product.getCategoryId());
		productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));
		productListVo.setMainimage(product.getMainImage());
		productListVo.setPrice(product.getPrice());
		productListVo.setSubtitle(product.getSubtitle());
		productListVo.setStatus(product.getStatus());
		return productListVo;
	}
	@Override
	public ServerResponse<PageInfo> productSearch(String productName, Integer productId , int pageNum, int pageSize){
		PageHelper.startPage(pageNum, pageSize);
		if(StringUtils.isNotBlank(productName)){
			productName = new StringBuilder().append("%").append(productName).append("%").toString();
		}
		List<Product> productList = productMapper.selectByNameAndProductId(productName, productId);
		List<ProductListVo> productListVoList = new ArrayList<ProductListVo>();
		for (Product product : productList) {
			ProductListVo productListVo = new ProductListVo();
			productListVo = this.assembleProductListVo(product);
			productListVoList.add(productListVo);
		}
		PageInfo pageResult = new PageInfo(productList);
		pageResult.setList(productListVoList);//传入分页信息
		return ServerResponse.createBySuccess(pageResult);
		
		
	}
	@Override
	public ServerResponse getProductDetail(Integer productId){
		if(productId == null){
			return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(),"参数错误");
			
		}
		Product product = productMapper.selectByPrimaryKey(productId);
		if(product == null){
			return ServerResponse.createByErrorMessage("产品已下架或者删除");
		}
		if(product.getStatus() != Const.ProductStatusEnum.ON_SALE.getCode()){
			return ServerResponse.createByErrorMessage("产品已下架或者删除");
		}
		ProductDetailVo productDetailVo = assembleProductDetailVo(product);
		return ServerResponse.createBySuccess(productDetailVo);
	}
	@Override
	public ServerResponse getProductByKeywordCategory(String keyword,Integer categoryId,int pageNum,int pageSize,String orderBy){
		if(StringUtils.isBlank(keyword) && categoryId == null){
			return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "参数错误");
		}
		List<Integer> categoryIdList = new ArrayList<Integer>();
		if(categoryId != null){
			Category category = categoryMapper.selectByPrimaryKey(categoryId);
			if(category ==null && StringUtils.isBlank(keyword)){
				//没有该分类，并且还没有关键字，这个时候返回一个空的结果集，不报错
				PageHelper.startPage(pageNum, pageSize);
				List<ProductListVo> productListVoList = Lists.newArrayList();
				PageInfo pageInfo = new PageInfo(productListVoList);
				return ServerResponse.createBySuccess(pageInfo);
			}
			categoryIdList = (List<Integer>) iCategoryService.getCategoryAndDeepChildrenCategory(categoryId).getData();
		}
		if(StringUtils.isNotBlank(keyword)){
			keyword = new StringBuilder().append("%").append(keyword).append("%").toString();
		}
		PageHelper.startPage(pageNum, pageSize);
		//排序处理
		if(StringUtils.isNotBlank(orderBy)){
			if(Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
				String[] orderByArray = orderBy.split("_");
				PageHelper.orderBy(orderByArray[0]+" "+orderByArray[1]);
			}
		}
		List<Product> productList = productMapper.selectByNameAndCategoryIds(StringUtils.isNotBlank(keyword)?keyword:null, categoryIdList.size() == 0? null:categoryIdList);
		List<ProductListVo> productListVoList = new ArrayList<ProductListVo>();
		for (Product product : productList) {
			ProductListVo productListVo = assembleProductListVo(product);
			productListVoList.add(productListVo);
		}
		PageInfo pageInfo = new PageInfo(productList);
		pageInfo.setList(productListVoList);
		return ServerResponse.createBySuccess(pageInfo);
	}
}
